//
//  MWHomepageController.m
//  XiRan-iOS
//
//  Created by Richfit on 2019/10/30.
//  Copyright © 2019 Wood. All rights reserved.
//

#import "MWHomepageController.h"
#import "MWModifyPhoneController.h"
#import "MWModifyEmailController.h"
#import "MWModifyNicknameController.h"

#import "MWHomepageCell.h"

@interface MWHomepageController () <UITableViewDataSource, UITableViewDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate>

@property(nonatomic, strong) UIView *headerView;
@property(nonatomic, strong) UIButton *avatarBtn;
@property(nonatomic, strong) UITableView *tableView;

@property(nonatomic, strong) MBProgressHUD *hud;

@end

@implementation MWHomepageController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = [[MWConfigManager manager] objectForKey:@"edit_info" defaultValue:@"编辑资料"];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    _tableView.backgroundColor = [UIColor whiteColor];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.tableHeaderView = self.headerView;
    [self.view addSubview:_tableView];
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self uploadAvatar];
    [_tableView reloadData];
}

- (void)uploadAvatar {
    if ([MWUserManager manager].user.avatar && [MWUserManager manager].user.avatar.length) {
        NSURL *url = [NSURL URLWithString:[MWUserManager manager].user.avatar];
        [_avatarBtn sd_setImageWithURL:url forState:UIControlStateNormal];
    }
}

- (void)avatarClick:(UIButton *)sender {
    [self showActionSheet];
}

#pragma mark - 选择图片
-(void)showActionSheet {
    NSString *camera = [[MWConfigManager manager] objectForKey:@"take_picture" defaultValue:@"拍照"];
    NSString *album = [[MWConfigManager manager] objectForKey:@"album" defaultValue:@"相册"];
    NSString *cancel = [[MWConfigManager manager] objectForKey:@"cancel" defaultValue:@"取消"];
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:camera style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UIImagePickerController *controller = [[UIImagePickerController alloc] init];
        controller.delegate = self;
        controller.allowsEditing = YES;
        controller.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:controller animated:YES completion:nil];
    }];
    
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:album style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UIImagePickerController *controller = [[UIImagePickerController alloc] init];
        controller.delegate = self;
        controller.allowsEditing = YES;
        controller.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentViewController:controller animated:YES completion:nil];
    }];
    
    UIAlertAction *action3 = [UIAlertAction actionWithTitle:cancel style:UIAlertActionStyleCancel handler:nil];
    [alert addAction:action1];
    [alert addAction:action2];
    [alert addAction:action3];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    [_avatarBtn setImage:image forState:UIControlStateNormal];
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    [self uploadAvatarWithImage:image];
}

#pragma mark - 上传头像
- (void)uploadAvatarWithImage:(UIImage *)image {
    NSMutableDictionary *paraDic = [[NSMutableDictionary alloc] init];
    
    _hud = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    _hud.label.text = [[MWConfigManager manager] objectForKey:@"loadin" defaultValue:@"加载中..."];
    
    MWWeakSelf
    [[MWNetworkManager manager] upload:kUploadUrl parameters:paraDic UIImage:image success:^(id responseObject) {
        NSDictionary *dic = responseObject;
        NSInteger code = [[dic objectForKey:@"code"] integerValue];
        NSString *msg = [dic objectForKey:@"msg"];
    
        if (code == 1) {
            NSDictionary *dataDic = [dic objectForKey:@"data"];
            [self modifyAvatar:[dataDic objectForKey:@"url"]];
        } else {
            weakSelf.hud.mode = MBProgressHUDModeText;
            weakSelf.hud.label.text = msg;
            [weakSelf.hud hideAnimated:YES afterDelay:2];
        }
        
    } failure:^(NSError * _Nonnull error) {
        [weakSelf.hud hideAnimated:YES];
    }];
}

#pragma mark - 修改头像
- (void)modifyAvatar:(NSString *)avatar {
    NSString *token = [MWUserManager manager].user.token;
    NSMutableDictionary *paraDic = [[NSMutableDictionary alloc] init];
    [paraDic setObject:token forKey:@"token"];
    [paraDic setObject:avatar forKey:@"avatar"];
    [paraDic setObject:[MWConfigManager manager].language forKey:@"language"];
    
    MWWeakSelf
    [[MWNetworkManager manager] POST:kModifyAvatarUrl parameters:paraDic progress:^(NSProgress *downloadProgress) {
        
    } success:^(id responseObject) {
        NSDictionary *dic = responseObject;
        NSInteger code = [[dic objectForKey:@"code"] integerValue];
        NSString *msg = [dic objectForKey:@"msg"];
        
        weakSelf.hud.mode = MBProgressHUDModeText;
        weakSelf.hud.label.text = msg;
        [weakSelf.hud hideAnimated:YES afterDelay:2];
        
        if (code == 1) {
            [MWUserManager manager].user.avatar = [dic objectForKey:@"data"];
            [self uploadAvatar];
        }
        
    } failure:^(NSError *error) {
        [weakSelf.hud hideAnimated:YES];
    }];
}

#pragma mark - UITableViewDataSource && UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 4;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 50;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.1f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.1f;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [[UIView alloc] initWithFrame:CGRectZero];
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] initWithFrame:CGRectZero];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"MWHomepageCell";
    MWHomepageCell *homepageCell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!homepageCell) {
        homepageCell = [[MWHomepageCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        homepageCell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    MWUser *user = [MWUserManager manager].user;
    
    if (indexPath.row == 0) {
        homepageCell.titleLB.text = [[MWConfigManager manager] objectForKey:@"nickname" defaultValue:@"昵称"];
        homepageCell.descLB.text = user.nickname;
        
    } else if (indexPath.row == 1) {
        homepageCell.titleLB.text = [[MWConfigManager manager] objectForKey:@"phone_num" defaultValue:@"手机号码"];
        homepageCell.descLB.text = user.mobile;
        
    } else if (indexPath.row == 2) {
        homepageCell.titleLB.text = [[MWConfigManager manager] objectForKey:@"email" defaultValue:@"邮箱"];
        homepageCell.descLB.text = user.email;
    } else if(indexPath.row == 3) {
        homepageCell.titleLB.text = @"Close the account";
        homepageCell.descLB.text = @"";
    }
    
    return homepageCell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        MWModifyNicknameController *controller = [[MWModifyNicknameController alloc] init];
        [self.navigationController pushViewController:controller animated:YES];
        
    } else if (indexPath.row == 1) {
       MWModifyPhoneController *controller = [[MWModifyPhoneController alloc] init];
       [self.navigationController pushViewController:controller animated:YES];
        
    } else if (indexPath.row == 2) {
       MWModifyEmailController *controller = [[MWModifyEmailController alloc] init];
       [self.navigationController pushViewController:controller animated:YES];
    } else if(indexPath.row == 3) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Note" message:@"Would you like to close your account?" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"Yes" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            [self logoutWithMobile:[MWUserManager manager].user.mobile];
        }];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"No" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            
        }];
        [alert addAction:cancelAction];
        [alert addAction:okAction];
        [self presentViewController:alert animated:YES completion:^{
            
        }];
    }
}

- (UIView *)headerView {
    if (!_headerView) {
        _headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 210)];
        
        _avatarBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _avatarBtn.frame = CGRectMake(kScreenWidth / 2 - 30, 75, 60, 60);
        _avatarBtn.layer.cornerRadius = 30;
        _avatarBtn.layer.masksToBounds = YES;
        [_avatarBtn setImage:[UIImage imageNamed:@"naodai"] forState:UIControlStateNormal];
        [_avatarBtn addTarget:self action:@selector(avatarClick:) forControlEvents:UIControlEventTouchUpInside];
        [_headerView addSubview:_avatarBtn];
    }
    return _headerView;
}

#pragma mark - 注销登录
- (void)logoutWithMobile:(NSString *)mobile {
    NSString *token = [MWUserManager manager].user.token;
    NSMutableDictionary *paraDic = [[NSMutableDictionary alloc] init];
    [paraDic setObject:token forKey:@"token"];
    [paraDic setObject:mobile forKey:@"mobile"];
    [paraDic setObject:[MWConfigManager manager].language forKey:@"language"];
    
    _hud = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    _hud.label.text = @"";
    
    MWWeakSelf
    [[MWNetworkManager manager] POST:kLogoutUrl parameters:paraDic progress:^(NSProgress *downloadProgress) {
        
    } success:^(id responseObject) {
        NSDictionary *dic = responseObject;
        NSInteger code = [[dic objectForKey:@"code"] integerValue];
        NSString *msg = [dic objectForKey:@"msg"];
        if (code == 1) {
            [MWUserManager manager].user = nil;
            [[MWUserManager manager] clearUser];
            
            [weakSelf.hud hideAnimated:YES];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"CloseTheAccountNotification" object:nil];
            [self.navigationController popViewControllerAnimated:YES];
        } else {
            weakSelf.hud.mode = MBProgressHUDModeText;
            weakSelf.hud.label.text = msg;
            [weakSelf.hud hideAnimated:YES afterDelay:2];
        }
        
    } failure:^(NSError *error) {
        [weakSelf.hud hideAnimated:YES];
    }];
}


@end
